var PageSection = new function(){
    var sectionMap = [];
    var maxDocumentHeight = $(document).height() - $(window).height() + 1;console.log(maxDocumentHeight)
    var currentIndex = null;
    function getAange(i, index){ return sectionMap[i].range[index] < 0 ? maxDocumentHeight + sectionMap[i].range[index] : sectionMap[i].range[index] }
    function checkIndex(currentPosition) {
        for(var i=0; i<sectionMap.length; i++){
            if(currentPosition >= getAange(i, 0) && currentPosition <= getAange(i, 1)){ currentIndex = i; break }
            currentIndex = null;
        }
    }
    /*window.onscroll = function(e){
        var currentPosition = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        //console.log($(document).height(),document.body.clientHeight)
        console.log($(window).height(), window.innerHeight)
    };*/
    $(window).scroll(function(e){
        var currentPosition = e.currentTarget.pageYOffset;console.log(currentPosition)
        if(currentIndex == null){
            checkIndex(currentPosition); if(currentIndex != null){ sectionMap[currentIndex].instage() }
        }else{
            if(currentPosition < getAange(currentIndex, 0) || currentPosition > getAange(currentIndex, 1)){
                sectionMap[currentIndex].outstage();
                checkIndex(currentPosition); if(currentIndex != null){ sectionMap[currentIndex].instage() }
            }
        }
    });
    this.add = function (range, handler) { sectionMap.push({range: range, instage: handler.instage || function(){}, outstage: handler.outstage || function(){} }) };
    this.refresh = function () { maxDocumentHeight = $(document).height() - $(window).height() + 1 };
};